//
//  TestPathControlWC.m
//  sandbox
//
//  Created by 杨岑 on 7/16/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "TestPathControlWC.h"


#define kURL    @"url"

#define kBOOKMARK_OPTIONS_RESOLVE   (NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithSecurityScope)
#define kBOOKMARK_OPTIONS_SAVE      (NSURLBookmarkCreationWithSecurityScope | NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess)


@interface TestPathControlWC ()
@property (weak) IBOutlet NSPathControl *pathControl;
@property (weak) IBOutlet NSPathControl *pathControl2;

@end

@implementation TestPathControlWC

- (void)windowDidLoad {
    [super windowDidLoad];
    
    self.pathControl.focusRingType = NSFocusRingTypeNone;
    self.pathControl.doubleAction = @selector(pathControl_doubleclick:);
    NSLog(@"%@", self.pathControl.registeredDraggedTypes);
    
    BOOL stale;
    NSError* error;
    NSData* data = [[NSUserDefaults standardUserDefaults] dataForKey:kURL];
    NSURL* savedUrl = [NSURL URLByResolvingBookmarkData:data options:kBOOKMARK_OPTIONS_RESOLVE relativeToURL:nil bookmarkDataIsStale:&stale error:&error];
    if (error)
    {
        NSLog(@"%@", error);
    }
    
    if (!savedUrl)
    {
        savedUrl = [NSURL fileURLWithPath:[@"~/Documents" stringByResolvingSymlinksInPath]];
    }
    [self.pathControl setURL:savedUrl];
    
    [self.pathControl2 setURL:self.pathControl.URL];
}

- (IBAction)pathControl_doubleclick:(id)sender {
    [self.pathControl setURL:self.pathControl.clickedPathComponentCell.URL];
    [self.pathControl2 setURL:self.pathControl.URL];
}

- (IBAction)pathControl_changed:(id)sender {
    [self.pathControl2 setURL:self.pathControl.URL];
    
    NSNumber* f;
    NSError* error;
    NSURL* fileUrl = self.pathControl.URL.filePathURL;
    [fileUrl getResourceValue:&f forKey:NSURLIsDirectoryKey error:&error];

    if (f.boolValue)
    {
        NSData* data = [fileUrl bookmarkDataWithOptions:kBOOKMARK_OPTIONS_SAVE includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
        if (error)
        {
            NSLog(@"%@", error);
        }
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:kURL];
    }
    else
    {
        NSLog(@"%@ is not a directory", fileUrl);
    }
}

- (IBAction)test_click:(id)sender {
    NSLog(@"URL: %@", self.pathControl.URL);
    NSLog(@"URL.path: %@", self.pathControl.URL.path);
    NSLog(@"URL.filePathURL: %@", self.pathControl.URL.filePathURL);
    NSLog(@"URL.filePathURL.path: %@", self.pathControl.URL.filePathURL.path);
}

- (void)pathControl:(NSPathControl *)pathControl willPopUpMenu:(NSMenu *)menu
{
    NSLog(@"%@", menu);
}

@end
